package xin.fallen.util;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.Callable;

/**
 * Created by itsxun on 16/12/2.
 */
public class TokenCourier {
    private static Logger logger = LoggerFactory.getLogger("logger");

    public static String getAccessToken() {
        String url = ConfigReader.getValue("token_url");
        String token = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet(UrlCooker.format(url));
            CloseableHttpResponse response = httpclient.execute(httpGet);
            try {
                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity entity = response.getEntity();
                    String _token = EntityUtils.toString(entity, "utf-8");
                    token = _token.substring(_token.lastIndexOf("SIEP_TOKEN") + 13, _token.lastIndexOf("\""));
                    EntityUtils.consume(entity);
                }
            } finally {
                response.close();
            }
        } catch (Exception e) {
            logger.error("请求token异常，原因是：{}", e.getMessage());
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                logger.error("httpclient关闭异常，原因是{}", e.getMessage());
            }
        }
        return token;
    }
}
